package com.luxf.base.domainevent.rocketmq.bootstrap;

import com.luxf.base.domainevent.model.MessageReceivedHistory;
import com.luxf.base.domainevent.model.MessageSentHistory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.EnumSet;

/**
 * 启动处理类
 *
 * @author fast66
 * 2021-06-22 8:39
 **/
public class DomainEventBootstrap implements ApplicationListener<ApplicationReadyEvent> {

    @Value("${spring.jpa.database-platform:}")
    private String databasePlatform;

    @Value("${spring.jpa.properties.hibernate.dialect:org.hibernate.dialect.PostgreSQLDialect}")
    private String dialect;

    @Resource
    private DataSource dataSource;

    private static final String DEFAULT_SCHEMA = "\"public\"";

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySetting(Environment.DATASOURCE, dataSource)
                .applySetting(Environment.DIALECT, StringUtils.hasText(databasePlatform) ? databasePlatform : dialect)
                .applySetting(Environment.DEFAULT_SCHEMA, DEFAULT_SCHEMA)
                .build();
        MetadataSources metadata = new MetadataSources(serviceRegistry);

        metadata.addAnnotatedClass(MessageReceivedHistory.class);
        metadata.addAnnotatedClass(MessageSentHistory.class);

        SchemaExport schemaExport = new SchemaExport();
        schemaExport.execute(EnumSet.of(TargetType.DATABASE, TargetType.STDOUT),
                SchemaExport.Action.CREATE,
                metadata.buildMetadata());
    }
}
